package com.yonyou.hxjy.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;

import com.yonyou.hxjy.utils.BuildToken;
import com.yonyou.hxjy.utils.HttpClientUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/bm")
public class bmController {
    @Value("${ys.config.appKey}")
    private String appKey;
    @Value("${ys.config.appSecret}")
    private String appSecret;
    @Value("${bodyEncryptionKey}")
    private String bodyEncryptionKey;
    @Value("${signEncryptionPrivateKey}")
    private String signEncryptionPrivateKey;
    @Value("${bodyDecryptionKey}")
    private String bodyDecryptionKey;
    @Value("${TARGET_URL}")
    private String TARGET_URL;
    @Value("${APP_ID}")
    private String APP_ID;
    @Value("${app_secret}")
    private String app_secret;
    @Value("${grant_type}")
    private String grant_type;

    private static final Logger LOGGER = LoggerFactory.getLogger(bmController.class);


    @RequestMapping("/getToken")
    public String getToken() throws Exception {

        Map<String,Object> map =new HashMap<>();
        map.put("app_id",APP_ID);
        map.put("app_secret",app_secret);
        map.put("grant_type",grant_type);
        String uri=TARGET_URL+"/openapi/app/v1/app/token";
        String s1 = JSONObject.toJSONString(map);
        Map<String, String> headerMap =new HashMap<>();
        headerMap.put("Content-Type","application/json");
        String s = HttpClientUtil.doPostJson(uri, s1, headerMap);
        System.out.println(s);
        JSONObject jsonObject = JSONObject.parseObject(s);
        // logger.info("jsonObject"+jsonObject);
        String code = jsonObject.getString("code");
        if(!"0".equals(code)){
            throw new Exception(jsonObject.getString("msg"));
        }
        String token=jsonObject.getJSONObject("data").getString("token");
        return token;

    }

    @RequestMapping("/payDetail")
    public String payDetail() throws Exception {
        BuildToken selfBuildToken=new BuildToken();
        String token = selfBuildToken.getToken(APP_ID,app_secret,grant_type,TARGET_URL);
        if (token==null){
            return "false";
        }

        String uri=TARGET_URL+"/openapi/payment/openapi/v2/detail";
        CloseableHttpClient client = HttpClients.custom()
                // 禁止HttpClient自动解压缩
                .disableContentCompression()
                .build();

        Map<String,Object> map =new HashMap<>();

        map.put("referenceNum","6779235174315876736911743386573645");
        HttpPost httpPost =SM2Example.setupRequest(map.toString(),signEncryptionPrivateKey,uri,bodyEncryptionKey,token);
        try (CloseableHttpResponse response = client.execute(httpPost)) {
            byte[] finalResponseData = SM2Example.handleResponse(response,bodyDecryptionKey);
            LOGGER.info("\n返回结果：{}", new String(finalResponseData));
        }catch (Exception ignored){
            throw new Exception("网络连接失败或超时！");
        }finally {
            client.close();
        }
        return null;
    }

    @RequestMapping("/jscs")
    public cn.hutool.json.JSONObject  settlemenTran(@RequestBody String param) throws Exception{
        BuildToken selfBuildToken=new BuildToken();
        cn.hutool.json.JSONObject datajson =JSONUtil.createObj();

        datajson.set("code","999");
        String token = selfBuildToken.getToken(APP_ID,app_secret,grant_type,TARGET_URL);
        if (token==null){
            datajson.set("code","999");
            datajson.set("msg","toekn 生成失败为空");
            return datajson;
        }

        String uri=TARGET_URL+"/openapi/payment/openapi/v1/payment-apply-common";
        CloseableHttpClient client = HttpClients.custom()
                // 禁止HttpClient自动解压缩
                .disableContentCompression()
                .build();

        HttpPost httpPost =SM2Example.setupRequest(param,signEncryptionPrivateKey,uri,bodyEncryptionKey,token);
        try (CloseableHttpResponse response = client.execute(httpPost)) {
            byte[] finalResponseData = SM2Example.handleResponse(response,bodyDecryptionKey);
            LOGGER.info("\n返回结果：{}", new String(finalResponseData));
            datajson= JSONUtil.parseObj(new String(finalResponseData));

        }catch (Exception ignored){
            datajson.set("code","999");
            datajson.set("msg","toekn 网络连接失败或超时");
            throw new Exception("网络连接失败或超时！");
        }finally {
            client.close();
        }




        return datajson;

    }















}
